package com.xl.sst.biz.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Service;
import org.springframework.ui.Model;
import com.xl.sst.biz.UsersBiz;
import com.xl.sst.dao.UsersDao;
import com.xl.sst.utill.MD5Utils;
import com.xl.sst.vo.Page;
import com.xl.sst.vo.Users;
@Service
public class UsersBizImpl implements UsersBiz{
	@Resource
	private UsersDao usersDao;

	public Users checkLogin(Users user) {
		// TODO Auto-generated method stub
		return usersDao.getUserByUser(user);
	}

	public Users getUser(String phone) {
		// TODO Auto-generated method stub
		return usersDao.selectUserByPhone(phone);
	}

	public int isUserExit(Users user) {
		// TODO Auto-generated method stub
		return usersDao.isUserExit(user);
	}

	public void updateUser(Users user) {
		usersDao.updateUser(user);
		
	}

	public Users checkUser(String phone, String password) {
		Users user=getUser(phone);
		if(user !=null){
			//密码
			String salt = user.getSalt();
			String saltPassword = MD5Utils.GetMD5Code(String.valueOf(password)+ salt);
			if(saltPassword.equals(user.getPassword())){
				return user;
			}
		}
		return null;
	}

	public Double getMyWallet(String userId) {
		
		return usersDao.selectMyWallet(userId);
	}

	public Users get(Integer userId) {
		
		return usersDao.getUserById(userId);
	}

	public Integer blockUp(Integer userId) {
		
		return usersDao.blockUp(userId);
	}

	public Page findAllUsers(Integer currentPage, Model model) {
		Page page=new Page();
		page.setRows(usersDao.selectUsersCount());
		page.setCurrentPage(currentPage);
		Map<String,Object> map=new HashMap<String,Object>();
		map.put("page", page.getBegin());
		map.put("pageSize", page.getPageSize());
		List<Map<String, Object>> list = usersDao.selectAllUsers(map);
		for(Map<String, Object>m:list){
			for(String key : m.keySet()){
				System.out.println(key+""+m.get(key));
			}
		}
		model.addAttribute("user",list);
		return page;
	}

	public int insertUser(Users user,HttpSession session) {
		String yzm=(String) session.getAttribute("yzm");
		Integer number = (int) (Math.random() * (9999 - 1000 + 1)) + 1000;
		String salt=number.toString();
		String saltPassword = MD5Utils.GetMD5Code(String.valueOf(user.getPassword())+ salt);
		user.setSalt(salt);
		user.setPassword(saltPassword);
		if(user.getYzm().equals(yzm)) {
		Users u = usersDao.selectUserByPhone(user.getPhone());
		if(u==null) {
			usersDao.insertUser(user);
			return 0;//注册成功
		}else {
			return 1;//注册失败
		}
	}else {
		return 2;
		}
	}
}
